<template>
  <div class="flex items-center justify-center">
    <div class="w-full max-w-md">
      <div class="flex items-center mb-6">
        <span class="text-xl flex-grow">个人信息</span>
      </div>

      <div class="flex justify-center mb-6">
        <div
          class="avatar w-[48px] h-[48px] bg-blue-200 rounded-full flex-center relative cursor-pointer"
        >
          <img :src="avatar" class="rounded-full" />
          <div
            class="avatar-edit rounded-full flex-center absolute w-full h-full opacity-0 bg-black/50"
            @click="uploadImg"
          >
            <span class="iconfont icon-pen_icon text-white"></span>
          </div>
        </div>
      </div>
      <input
        class="hidden"
        type="file"
        accept="image/*"
        ref="imgReader"
        @change="loadingImg"
      />
      <div class="space-y-4 text-[14px]">
        <div class="flex justify-between items-center">
          <span class="text-gray-600">{{ $t("message.username") }}</span>
          <span class="text-color-t3 cursor-pointer"
            >{{ info.account }}
            <i class="iconfont icon-arrow_icon text-[#3a3a3c]"></i
          ></span>
        </div>
        <div
          class="flex justify-between items-center"
          @click="visibleUpdatePwd = true"
        >
          <span class="text-gray-600">{{ $t("message.password") }}</span>
          <span class="text-color-t3 cursor-pointer"
            >•••••••••<i
              class="iconfont icon-arrow_icon text-[#3a3a3c] text-[12px]"
            ></i
          ></span>
        </div>
      </div>

      <button
        class="mt-8 w-full bg-white border border-gray-300 text-gray-700 py-2 px-4 rounded-md hover:bg-gray-50 transition-colors"
        @click="logout"
      >
        {{ $t("message.logout") }}
      </button>

      <Teleport to="#app">
        <ClipImage
          v-on-click-outside="closeModal"
          ref="clipImageRef"
          v-show="visibleClipImage"
          @close="visibleClipImage = false"
          @confirm="confirmImg"
          @operate="operateImg"
        ></ClipImage>
      </Teleport>
    </div>
  </div>
  <div
    class="absolute pointer-events-none inset-0 flex items-center"
    style="z-index: 125"
    v-if="visibleUpdatePwd"
  >
    <div
      class="w-full flex-1 px-[20px] max-h-[calc(100vh-40px)]"
      style="height: auto"
    >
      <div
        class="pointer-events-auto relative mx-auto h-full overflow-hidden bg-color-b3 shadow-dialog dark:bg-color-b5 rounded-[12px]"
        style="max-width: 300px"
      >
        <UpdatePwd
          @close="visibleUpdatePwd = false"
          @passwordChanged="passwordChanged"
        ></UpdatePwd>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { vOnClickOutside } from "@vueuse/components";
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import loginApi from "../api/login";
import fileApi from "../api/file";
import type { UserInfo as UserInfoType } from "../api/setting";
import settingApi from "../api/setting";
import UpdatePwd from "../elements/UpdatePwd.vue";
import ClipImage from "../elements/ClipImage.vue";
// @ts-ignore
import smCrypto from "../utils/smCrypto.js";
import { useUserInfoStore, useSettingStore } from "../store";

const userInfoStore = useUserInfoStore();
const settingStore = useSettingStore();
const info = ref<UserInfoType>(userInfoStore.userInfo);

const avatar = computed(() => {
  return settingStore.setting.avatar || userInfoStore.userInfo.avatar;
});

let CROPPER; //创建一个cropper的全局对象
const imgReader = ref<HTMLElement | null>(null);

const visibleClipImage = ref(false);

const closeModal = () => {
  visibleClipImage.value = false;
};
const logout = () => {
  loginApi.logout().then(() => {
    // 刷新页面
    localStorage.removeItem("token");
    location.reload();
  });
};
const visibleUpdatePwd = ref(false);

const passwordChanged = (obj) => {
  // obj.password = smCrypto.doSm2Encrypt(obj.password);
  // obj.newPassword = smCrypto.doSm2Encrypt(obj.newPassword);
  loginApi.updatePwd(obj).then((res) => {
    visibleUpdatePwd.value = false;
  });
};
const clipImageRef = ref<InstanceType<typeof ClipImage> | null>(null);
const loadingImg = (event) => {
  //读取上传文件
  let reader = new FileReader();
  if (event.target.files[0]) {
    //readAsDataURL方法可以将File对象转化为data:URL格式的字符串（base64编码）
    reader.readAsDataURL(event.target.files[0]);
    reader.onload = (e) => {
      visibleClipImage.value = true;
      let dataURL = reader.result;
      //将img的src改为刚上传的文件的转换格式
      const cropImg = clipImageRef.value.img as HTMLImageElement;
      if (cropImg) {
        cropImg.src = dataURL as string;
        if (CROPPER) {
          // CROPPER.destroy();
          CROPPER.replace(dataURL as string);
        } else {
          // 创建新的 Cropper 实例
          CROPPER = new Cropper(cropImg, {
            aspectRatio: 16 / 16,
            viewMode: 0,
            dragMode: "move",
          });
        }
      }
    };
  }
  event.target.value = "";
};

const uploadImg = () => {
  imgReader.value?.click();
};
const updateSetting = (data) => {
  settingApi.edit(data).then((res) => {
    settingStore.setSetting(data);
  });
};

const confirmImg = () => {
  CROPPER.getCroppedCanvas({
    width: 48,
    height: 48,
    fillColor: "#fff",
    imageSmoothingEnabled: false,
    imageSmoothingQuality: "high",
  }).toBlob((blob) => {
    const formData = new FormData();
    formData.append("file", blob);
    fileApi
      .fileUploadLocalReturnUrl(formData)
      .then((response) => {
        // 更新个人头像信息
        updateSetting({ avatar: response });
        closeModal();
      })
      .catch((err) => {
        console.log(err);
      });
  });
};

const operateImg = (type) => {
  switch (type) {
    case "leftRotate":
      CROPPER.rotate(-90);
      break;
    case "rightRotate":
      CROPPER.rotate(90);
      break;
    case "shrink":
      CROPPER.zoom(-0.1);
      break;
    case "enlarge":
      CROPPER.zoom(0.1);
      break;
    case "reset":
      CROPPER.reset();
      break;
  }
};
</script>

<style lang="scss" scoped>
.iconfont.icon-arrow_icon {
  font-size: 12px;
  margin-left: 12px;
}
.avatar {
  &:hover {
    .avatar-edit {
      opacity: 1;
    }
  }
}
</style>
